package com.spring.mqtt;

import com.spring.mqtt.annotation.MqttSubscirbe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class MqttSubscribeProcessor {
    @Autowired
    MqttPahoMessageDrivenChannelAdapter adapter;
    @Autowired
    MqttUtilsBean mqttUtilsBean;

    List<String> topics = new ArrayList<>();
    
    @Bean
    public void subscribe() {
        for (Object o : mqttUtilsBean.getControllerBeans()) {
            Method[] methods = o.getClass().getMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(MqttSubscirbe.class)) {
                    MqttSubscirbe mqttSubscirbe = method.getAnnotation(MqttSubscirbe.class);
                    String topic = mqttSubscirbe.topic();
                    int qos = mqttSubscirbe.qos();

                    topic = MqttTopicUtils.getSubscribeTopic(topic);
                    topics.add(topic);
                    adapter.addTopic(topic,qos);
                    log.info("add subscribe topic: "+topic +"  qos:"+ qos);
                }
            }
        }
    }
}
